import axios from "axios";
import { message } from "ant-design-vue";

import { getLocal } from "./storage";

let isTokenExpired = false;
const activeRequests = new Set();

const instance = axios.create({
  baseURL: "/api",
  timeout: 25000,
  headers: {
    "Content-type": "application/json;charset=utf-8",
  },
});

let whiteList = [
  "/permission/login",
  "/permission/register",
  "/permission/system/info",
];
instance.interceptors.request.use((config) => {
  let token = getLocal("ss_token");
  if (!token) {
    if (!whiteList.includes(config.url)) {
      message.warning("请先前往登录~");
      setTimeout(() => {
        window.location.href = "/login";
      }, 1000);
      return Promise.reject();
    } else {
      return config;
    }
  } else {
    if (isTokenExpired) {
      return Promise.reject(new axios.Cancel("Token已过期"));
    }
    const controller = new AbortController();
    config.signal = config.signal ?? controller.signal;
    activeRequests.add(controller);
    config.headers["Authorization"] = "Bearer " + token;
    return config;
  }
});

instance.interceptors.response.use(
  (response) => {
    if (response.data.code === 0) {
      return response.data;
    } else if (response.data.code === 40001) {
      isTokenExpired = true;
      activeRequests.forEach((controller) => controller.abort());
      activeRequests.clear();
      message.error(response.data.message);
      setTimeout(() => {
        window.location.href = "/login";
      }, 1000);
    } else {
      message.error(response.data.message);
    }
  },
  (error) => {
    if (!error.response) {
      return Promise.reject(error);
    }
  }
);

export default instance;
